package com.xiongjie;

import com.xiongjie.impl.IPerson;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.serviceproxy.ServiceException;
import io.vertx.serviceproxy.ServiceExceptionMessageCodec;

public class IPersonVertxEBProxy implements IPerson {

    private Vertx _vertx;
    private String _address;
    private DeliveryOptions _options;
    private boolean closed;

    public IPersonVertxEBProxy(Vertx vertx, String address) {
        this(vertx, address, null);
    }

    public IPersonVertxEBProxy(Vertx vertx, String address, DeliveryOptions options) {
        this._vertx = vertx;
        this._address = address;
        this._options = options;
        try{
            this._vertx.eventBus().registerDefaultCodec(ServiceException.class, new ServiceExceptionMessageCodec());
        } catch (IllegalStateException ex) {}
    }

    @Override
    public void getPersonByName(String name, Handler<AsyncResult<JsonObject>> resultHandler) {
        if (closed) {
            resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
            return;
        }
        JsonObject _json = new JsonObject();
        _json.put("name", name);

        DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
        _deliveryOptions.addHeader("action", "getPersonByName");
        _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
            if (res.failed()) {
                resultHandler.handle(Future.failedFuture(res.cause()));
            } else {
                resultHandler.handle(Future.succeededFuture(res.result().body()));
            }
        });
    }
}
